package com.wxw.BaseLibrary.tool;


import com.wxw.BaseLibrary.infa.AsynEventListener;

/**
 * Created by david on 2016-05-17.
 */
public class ThreadPoster<T> implements Runnable {
    public static final int COMMAND_START = 0;
    public static final int COMMAND_RESPONSE = 1;
    public static final int COMMAND_FINISH = 2;

    private int what;
    private AsynEventListener asynEventListener;

    private int command;
    private T t;
    private Exception exception = null;

    public ThreadPoster(int what, AsynEventListener<?> listener) {
        this.what = what;
        this.asynEventListener = listener;
    }

    public void onStart() {
        this.command = COMMAND_START;
    }

    public void onResponse(T t, Exception e) {
        this.command = COMMAND_RESPONSE;
        this.t = t;
        this.exception = e;
    }

    public void onFinished() {
        this.command = COMMAND_FINISH;
    }
    @Override
    public void run() {
        if (asynEventListener != null) {
            if (command == COMMAND_START) {
                asynEventListener.onStart(what);
            } else if (command == COMMAND_FINISH) {
                asynEventListener.onFinish(what);
            } else if (command == COMMAND_RESPONSE) {
                if (t == null) {
                    asynEventListener.onFailed(what, null,(exception==null? new Exception("Unknown abnormal."):exception));
                } else {
                    if (exception != null) {
                        asynEventListener.onFailed(what, null, exception);
                    } else {
                        asynEventListener.onSucceed(what, t);
                    }
                }
            }
        }
    }
}
